package com.leadingsoft.pwxk.service.impl;

import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.leadingsoft.pwxk.converter.AnnouncementConverter;
import com.leadingsoft.pwxk.dto.AnnouncementDto;
import com.leadingsoft.pwxk.dto.SearchDto;
import com.leadingsoft.pwxk.model.Announcement;
import com.leadingsoft.pwxk.model.QAnnouncement;
import com.leadingsoft.pwxk.repository.AnnouncementRepository;
import com.leadingsoft.pwxk.service.AnnouncementService;
import com.querydsl.core.BooleanBuilder;

@Service
public class AnnouncementServiceImpl implements AnnouncementService {

	QAnnouncement qAnnouncement = QAnnouncement.announcement;
	@Autowired
	AnnouncementRepository announcementRepository;

	@Autowired
	AnnouncementConverter announcementConverter;

	@Override
	@Transactional
	public Announcement save(AnnouncementDto ann) {
		Announcement announcement = new Announcement();
		announcementConverter.copyProperties(announcement, ann);
		Date date = new Date();
		announcement.setFbTime(date);
		announcement.setUpdateTime(date);
		return announcementRepository.save(announcement);
	}

	@Override
	@Transactional
	public Announcement update(AnnouncementDto ann) {
		Announcement announcement = new Announcement();
		announcementConverter.copyProperties(announcement, ann);
		announcement.setUpdateTime(new Date());
		return announcementRepository.save(announcement);
	}

	@Override
	@Transactional
	public void delete(Long id) {
		announcementRepository.deleteById(id);
	}

	@Override
	public Announcement get(Long id) {
		return announcementRepository.getOne(id);
	}

	@Override
	public Page<Announcement> getList(SearchDto s, Pageable pageable) {
		BooleanBuilder booleanBuilder = new BooleanBuilder();
		if (StringUtils.isNotBlank(s.getTitle())) {
			booleanBuilder.and(qAnnouncement.title.eq(s.getTitle()));
		}
		return announcementRepository.findAll(booleanBuilder.getValue(), pageable);
	}

	@Override
	public List<Announcement> getTop7() {
		return announcementRepository.findTop7ByOrderByUpdateTimeDesc();
	}

}
